package com.akk.business;

import com.akk.PayConstants;
import com.akk.common.enums.Enums;
import com.akk.common.enums.UserCardEnums;
import com.akk.module.access.entity.Access;
import com.akk.module.access.entity.AccessBind;
import com.akk.module.access.service.AccessService;
import com.akk.module.avs.entity.AvsCustomer;
import com.akk.module.avs.entity.AvsPayAccess;
import com.akk.module.avs.entity.AvsPayOrder;
import com.akk.module.avs.entity.AvsPayVip;
import com.akk.module.avs.enums.AvsPayHlbH5Enums;
import com.akk.module.avs.enums.AvsPayVipStatus;
import com.akk.module.avs.model.request.DepositRequest;
import com.akk.module.avs.service.AvsCustomerService;
import com.akk.module.avs.service.AvsPayAccessService;
import com.akk.module.avs.service.AvsPayOrderService;
import com.akk.module.avs.service.AvsPayVipService;
import com.akk.module.hlbpay.model.HlbH5CallBackRequest;
import com.akk.module.hlbpay.model.HlbH5PayRequest;
import com.akk.module.hlbpay.service.Hlbh5Service;
import com.akk.module.hlbpay.util.Disguiser;
import com.akk.utils.IPUtil;
import com.akk.utils.RestResponse;
import com.akk.utils.rsa.RSAUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by admin on 2017/11/11.
 * 合利宝H5
 */

@Component
public class AvsHlbH5Business {

    @Autowired
    private Hlbh5Service hlbh5Service;
    @Autowired
    private AvsPayOrderService avsPayOrderService;
    @Autowired
    private AvsCustomerService avsCustomerService;
    @Autowired
    private AvsPayVipService avsPayVipService;
    @Autowired
    private AccessService accessService;
    @Autowired
    private AvsPayAccessService avsPayAccessService;
    @Value("${server.url}")
    private String serverUrl;
    @Autowired
    private AvsPayBusiness payBusiness;

    // h5快捷支付
    public RestResponse h5QuickPay(String bindId, String orderNum, HttpServletRequest servletRequest) {
        List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(orderNum);
        if (orders.size() == 0) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单不存在");
        }
        AvsPayOrder order = orders.get(0);
        AvsCustomer customer = avsCustomerService.findByCustomerId(order.getPayerId());
        if (customer == null){
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"用户信息错误");
        }
        List<AvsPayVip> vips = avsPayVipService.findByUserId(customer.getCustomerId());
        if (vips.size() == 0){
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"用户信息不存在。");
        }
        AvsPayVip vip = vips.get(0);
        if (order.getRemark().equals(PayConstants.VIP_CASH)
                && vip.getEndTime() != null
                && vip.getEndTime().compareTo(new Date()) > 0){
            if (vip.getStatus() == AvsPayVipStatus.VipStatus.VIP.getValue()){
                return RestResponse.build(RestResponse.AVS_ERROR_CODE,"您已经是VIP用户。");
            }
        }else {
            if (!order.getRemark().equals(PayConstants.VIP_CASH)){
                if (vip.getStatus() == AvsPayVipStatus.VipStatus.NORMAL.getValue()){
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE,"此功能仅限VIP使用");
                }else if (vip.getStatus() == AvsPayVipStatus.VipStatus.BLACK.getValue()){
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE,"此用户已被拉黑，详情请联系客服。");
                }else if ( vip.getEndTime() != null && vip.getEndTime().compareTo(new Date()) < 0){
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE,"VIP已到期。");
                }
            }
        }
        Access access = accessService.findByAccessId(order.getAccessId());
        if (access == null){
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"通道信息有误");
        }else if (access.getAccessStatus() != 1){
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"通道不可用");
        }
        List<AvsPayAccess> payAccess = avsPayAccessService.queryByAccessId(access.getAccessId());
        if (payAccess.isEmpty()){
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"通道信息有误");
        }else if (payAccess.get(0).getPayStatus() != 1){
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"通道不可用");
        }
        AccessBind accessBind = accessService.findAccessBindById(bindId);
        if (accessBind == null){
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"银行卡信息不存在");
        }
        order.setPayCardNo(accessBind.getCardNum());
        order.setPayBank(accessBind.getCardName());
        avsPayOrderService.update(order);
        HlbH5PayRequest request = new HlbH5PayRequest();
        request.setP3_userId(order.getPayerId());
        request.setP4_orderId(order.getOrderNum());
        request.setP5_timestamp(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        request.setP6_goodsName(order.getRemark());
        request.setP7_orderAmount(order.getAmountTotal().toString());
        request.setP9_period("");
        request.setP10_periodUnit("");
        request.setP11_payerName(customer.getCustomerName());
        request.setP12_idCardType("IDCARD");
        request.setP13_idCardNo(customer.getIdCard());
        request.setP14_cardNo(accessBind.getCardNum());
        if (accessBind.getCardType().equals(UserCardEnums.CardType.XINYONG.getValue())){
            if (!StringUtils.isEmpty(accessBind.getCvv2())){
                accessBind.setCvv2(RSAUtils.decryptDataOnJava(accessBind.getCvv2(),PayConstants.CARD_RSA_PRIVATE_KEY_PKCS8));
            }
            if (!StringUtils.isEmpty(accessBind.getValidity())){
                accessBind.setValidity(RSAUtils.decryptDataOnJava(accessBind.getValidity(),PayConstants.CARD_RSA_PRIVATE_KEY_PKCS8));
            }
            request.setP15_year(StringUtils.isEmpty(accessBind.getValidity()) ? "" : accessBind.getValidity().substring(2,4));
            request.setP16_month(StringUtils.isEmpty(accessBind.getValidity()) ? "" : accessBind.getValidity().substring(0,2));
            request.setP17_cvv2(accessBind.getCvv2());
        }
        request.setP18_phone(accessBind.getPhone());
        request.setP19_callbackUrl(serverUrl+"/thmlfApi/avs/hlbh5/quickpaycallback?payerId="+customer.getCustomerId()+"&appId="+customer.getAppId());
        request.setP20_serverCallbackUrl(serverUrl+"/thmlfApi/avs/hlbh5/quickpayservercallback");
        request.setP21_orderIp(IPUtil.getIpAddress(servletRequest));
        request.setP24_desc(order.getRemark());
        return RestResponse.build(hlbh5Service.payRequest(request));
    }


    // 回调地址
    public String quickPayCallBack(String appId, String payerId, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.sendRedirect(serverUrl+"/pay/cash.html?appId="+appId+"&payerId="+payerId);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    // 支付通知
    public String quickPayServerCallBack(HlbH5CallBackRequest request) {
        String sign = request.getSignStr();
        sign = Disguiser.disguiseMD5(sign);
        if (request.getSign().equals(sign)){
            List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(request.getRt4_orderId());
            if (orders.size() == 0){
                return "error";
            }
            AvsPayOrder order = orders.get(0);
            if (Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue()) || Objects.equals(order.getStatus(), Enums.OrderStatusEnum.VIP_SUCCESS.getValue())){
                return "success";
            }
            if (AvsPayHlbH5Enums.OrderResStatus.SUCCESS.getValue().equals(request.getRt8_orderStatus())){
                order.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
                avsPayOrderService.update(order);
                Date date = null;
                try {
                    date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(request.getRt7_completeDate());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                order.setTransDate(date);
                if (order.getRemark().equals(PayConstants.VIP_CASH)){
                    List<AvsPayVip> vips = avsPayVipService.findByUserId(order.getPayerId());
                    if (vips.size() > 0){
                        AvsPayVip vip = vips.get(0);
                        vip.setStatus(AvsPayVipStatus.VipStatus.VIP.getValue());
                        Date nowDate = new Date();
                        Calendar c = Calendar.getInstance();
                        //一年后
                        c.setTime(nowDate);
                        c.add(Calendar.YEAR, 1);
                        Date nextYear = c.getTime();
                        vip.setPayTime(nowDate);
                        vip.setEndTime(nextYear);
                        vip.setMoney(order.getAmountTotal());
                        avsPayVipService.update(vip);
                        order.setStatus(Enums.OrderStatusEnum.VIP_SUCCESS.getValue());
                        order.setFinishDate(new Date());
                        avsPayOrderService.update(order);
                    } else {
                        order.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
                        avsPayOrderService.update(order);
                    }
                    return "success";
                }
                DepositRequest depositRequest = new DepositRequest();
                depositRequest.setOrderNum(order.getOrderNum());
                depositRequest.setAmount(order.getAmountTotal().toString());
                depositRequest.setPayerId(order.getPayerId());
                depositRequest.setSummary(order.getRemark());
                RestResponse restResponse = payBusiness.deposit(depositRequest);
                order = avsPayOrderService.findByOrderNum(request.getRt4_orderId()).get(0);
                if (restResponse.getCode().equals("200")){
                    System.out.println("提现成功");
                    order.setStatus(Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue());
                    order.setFinishDate(new Date());
                }else {
                    order.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
                    System.out.println(restResponse.getMessage());
                }
                avsPayOrderService.update(order);
                return "success";
            }else if (AvsPayHlbH5Enums.OrderResStatus.INIT.getValue().equals(request.getRt8_orderStatus())){
                order.setStatus(Enums.OrderStatusEnum.NO_PAYED.getValue());
            }else if (AvsPayHlbH5Enums.OrderResStatus.CANCELLED.getValue().equals(request.getRt8_orderStatus())){
                order.setStatus(Enums.OrderStatusEnum.CANCEL.getValue());
            }else if (AvsPayHlbH5Enums.OrderResStatus.DOING.getValue().equals(request.getRt8_orderStatus())){
                order.setStatus(Enums.OrderStatusEnum.DOING.getValue());
            }else if (AvsPayHlbH5Enums.OrderResStatus.FAILED.getValue().equals(request.getRt8_orderStatus())){
                order.setStatus(Enums.OrderStatusEnum.FAILED.getValue());
            }else if (AvsPayHlbH5Enums.OrderResStatus.REFUNDED.getValue().equals(request.getRt8_orderStatus())){
                order.setStatus(Enums.OrderStatusEnum.REFUNDING.getValue());
            }
            avsPayOrderService.update(order);
            return "success";
        }else {
            System.out.println("签名验证失败");
            return "error";
        }
    }

    @Test
    public void test(){
//        System.out.println(RSAUtils.decryptDataOnJava());
    }

}
